package model.symbol;

import lang.asm.DataTypeUtil;
import model.code.CodeFileChunk;
import model.code.Function;
import model.code.Rowable;
import model.code.line.NameLine;
import model.code.line.SingleLine;
import model.code.line.TypeLine;

/**
 * This class is for local variables of {@link model.code.Function}s.
 *
 * @author Neil Dickson
 */
public class LocalVariable extends Rowable implements Symbol {
	private final long		id;

	/**
	 * This is because Java can't do virtual static functions
	 */
	public static final LocalVariable	DUMMY_LOCAL_VAR = new LocalVariable("","","",null,CodeFileChunk.LOCATION_LOCAL_VARS,0);
	public static final LocalVariable	DUMMY_PARAM = new LocalVariable("","","",null,CodeFileChunk.LOCATION_PARAMETERS,0);

	public static final int	NAME_INDEX			= 0;
	public static final int	TYPE_INDEX			= 1;
	public static final int	DESCRIPTION_INDEX	= 2;
	public static final int	NUM_STRINGS			= 3;

	public LocalVariable(String name, String type, String description, CodeFileChunk parent, int locationType, int row) {
		super(NUM_STRINGS,parent,locationType,row);
		id = Scope.getUniqueID();
		strings[NAME_INDEX] = new NameLine(name.toCharArray(),parent,locationType,(row<<16)+NAME_INDEX,this);
		strings[TYPE_INDEX] = new TypeLine(type.toCharArray(),parent,locationType,(row<<16)+TYPE_INDEX);
		strings[DESCRIPTION_INDEX] = new SingleLine(description.toCharArray(),parent,locationType,(row<<16)+DESCRIPTION_INDEX);
	}

	public NameLine getName() {
		return (NameLine)strings[NAME_INDEX];
	}

	public SingleLine getDescription() {
		return strings[DESCRIPTION_INDEX];
	}

	public TypeLine getType() {
		return (TypeLine)strings[TYPE_INDEX];
	}

	public long getID() {
		return id;
	}

	public LocalVariable copy(CodeFileChunk parent, int row) {
		return new LocalVariable(getName().toString(),getType().toString(),getDescription().toString(),parent,getName().getLocationType(),row);
	}

	public String toString() {
		return getName().toString();
	}

	public void nowHaveGlobalScope() {
		getType().reparse();
	}

	/**
	 * Determines the size of the local variable
	 * @return the size of the local variable, or 0 if unable to do so
	 */
	public int getTypeSize() {
		TypeLine typeLine = getType();
		Function function = (Function)typeLine.getParent();
		if (function!=null && function.getLanguage()!=null && function.getGlobalScope()!=null) {
			DataType type = DataTypeUtil.getDataType(typeLine.toString(),function.getLanguage().getScope(),function.getGlobalScope(),function.getMode());
			if (type!=null) {
				return type.getSize();
			}
		}
		return 0;
	}
}
